package com.fx.ruankao.service.impl;

import com.fx.ruankao.entity.UserAnswer;
import com.fx.ruankao.entity.PaperQuestion;
import com.fx.ruankao.entity.ExamRecord;
import com.fx.ruankao.mapper.UserAnswerMapper;
import com.fx.ruankao.mapper.PaperQuestionMapper;
import com.fx.ruankao.mapper.ExamRecordMapper;
import com.fx.ruankao.service.UserAnswerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户答案服务实现类
 */
@Service
@Transactional
public class UserAnswerServiceImpl implements UserAnswerService {

    @Autowired
    private UserAnswerMapper userAnswerMapper;
    
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;
    
    @Autowired
    private ExamRecordMapper examRecordMapper;
    
    @Override
    public int insert(UserAnswer userAnswer) {
        return userAnswerMapper.insert(userAnswer);
    }
    
    @Override
    public int deleteById(Integer id) {
        return userAnswerMapper.deleteById(id);
    }
    
    @Override
    public int update(UserAnswer userAnswer) {
        return userAnswerMapper.update(userAnswer);
    }
    
    @Override
    public UserAnswer selectById(Integer id) {
        return userAnswerMapper.selectById(id);
    }
    
    @Override
    public List<UserAnswer> selectByRecordId(Integer recordId) {
        return userAnswerMapper.selectByRecordId(recordId);
    }
    
    @Override
    public int batchInsert(List<UserAnswer> userAnswers) {
        return userAnswerMapper.batchInsert(userAnswers);
    }
    
    @Override
    public int deleteByRecordId(Integer recordId) {
        return userAnswerMapper.deleteByRecordId(recordId);
    }
    
    @Override
    public List<UserAnswer> selectByUserIdAndPaperId(Integer userId, Integer paperId) {
        return userAnswerMapper.selectByUserIdAndPaperId(userId, paperId);
    }
    
    @Override
    public Integer calculateScore(Integer recordId) {
        if (recordId == null) {
            throw new IllegalArgumentException("考试记录ID不能为空");
        }
        
        try {
            // 1. 根据考试记录ID获取考试记录信息，得到试卷ID
            ExamRecord examRecord = examRecordMapper.selectById(Long.valueOf(recordId));
            if (examRecord == null) {
                throw new IllegalArgumentException("未找到考试记录");
            }
            
            Long paperId = examRecord.getPaperId();
            if (paperId == null) {
                throw new IllegalArgumentException("考试记录中未找到试卷ID");
            }
            
            // 2. 根据试卷ID查询所有题目及其分值
            List<PaperQuestion> paperQuestions = paperQuestionMapper.selectByPaperId(paperId);
            if (paperQuestions == null || paperQuestions.isEmpty()) {
                throw new IllegalArgumentException("该试卷未配置题目");
            }
            
            // 将题目ID与分值映射存储在Map中，方便快速查找
            Map<Long, Double> questionScoreMap = new HashMap<>();
            for (PaperQuestion paperQuestion : paperQuestions) {
                questionScoreMap.put(paperQuestion.getQuestionId(), paperQuestion.getScore());
            }
            
            // 3. 根据考试记录ID查询所有用户答案
            List<UserAnswer> userAnswers = userAnswerMapper.selectByRecordId(recordId);
            if (userAnswers == null || userAnswers.isEmpty()) {
                return 0; // 没有答题记录，返回0分
            }
            
            // 4. 计算总分
            double totalScore = 0;
            for (UserAnswer userAnswer : userAnswers) {
                // 只有答题正确且题目有分值配置的情况下才加分
                if (userAnswer.getIsCorrect() != null && userAnswer.getIsCorrect()) {
                    Long questionId = userAnswer.getQuestionId();
                    if (questionId != null && questionScoreMap.containsKey(questionId)) {
                        Double questionScore = questionScoreMap.get(questionId);
                        if (questionScore != null) {
                            totalScore += questionScore;
                            // 更新用户答案的得分
                            userAnswer.setScore(questionScore);
                            userAnswerMapper.update(userAnswer);
                        }
                    }
                }
            }
            
            // 5. 更新考试记录的总分
            examRecord.setTotalScore(totalScore);
            examRecord.setStatus(2); // 设置为已完成状态
            examRecord.setEndTime(new java.util.Date()); // 设置结束时间
            examRecordMapper.update(examRecord);
            
            // 返回整数类型的总分
            return (int) Math.round(totalScore);
        } catch (Exception e) {
            // 实际项目中应该使用日志记录异常
            throw new RuntimeException("计算成绩失败: " + e.getMessage(), e);
        }
    }
    
    @Override
    public int countAnswers() {
        // 由于Mapper接口中没有直接的countAnswers方法，我们可以通过查询所有记录并获取数量来实现
        // 注意：这不是最高效的实现，实际项目中应该添加专门的count方法
        return userAnswerMapper.batchInsert(new java.util.ArrayList<>());
    }
    
    @Override
    public int countAnswersByPaperId(Integer paperId) {
        // 使用Mapper接口中定义的countByPaperId方法
        return userAnswerMapper.countByPaperId(paperId);
    }
}